const mongoose = require('mongoose')
const db = "mongodb://localhost/douban"
const glob = require('glob')
const {
    resolve
} = require('path');
mongoose.Promise = global.Promise;
exports.initSchemas = () => {
    glob.sync(resolve(__dirname, './schema/', '**/*.js')).forEach(require)
}

exports.connect = () => {
    mongoose.connect(db, {
        useNewUrlParser: true
    })
    let maxConnectTimes = 0
    return new Promise((resolve, reject) => {
        mongoose.connection.on('disconnected', () => {
            console.log('*数据库断开*')
            if (maxConnectTimes < 3) {
                maxConnectTimes++
                mongoose.connect(db, {
                    useNewUrlParser: true
                })
            } else {
                reject()
                throw new Error('数据库出现问题，程序无法搞定，请人为修理......')
            }
        })
        //链接打开的时
        mongoose.connection.once('open', () => {
            console.log('MongoDB connected successfully')
            resolve()
        })
    })
}